from easymoney.business.file import image_service
from easymoney.business.stock.webdriver import stock_info_service
from easymoney.dao import investment_recom_dao
from easymoney.ocr.easy_ocr import ocr

from peewee import IntegrityError

"""
对文件目录下的所有股票图片 jpg 进行 ocr 扫描，并将结果更新到 mysql 
"""


def process_jpg_files(directory_path):
    """
    遍历指定目录下的所有 JPG 文件，进行 OCR 扫描，并更新 MySQL 数据库。
    """
    jpg_file_list = image_service.traverse_jpg_files(directory_path)
    for file_name in jpg_file_list:
        print(f"start process {file_name}")
        process_single_file(file_name)


def process_single_file(file_name):
    """
    对单个 JPG 文件进行 OCR 扫描，并处理扫描结果。
    """
    stock_code_list = ocr(file_name)  # OCR 图片扫描
    for code in stock_code_list:
        # 通过股票 code ，爬虫读取股票对应的名称
        result = stock_info_service.get_stock_info_crawler(code)
        if result and '股票名称' in result:
            handle_stock_info(code, result)


def handle_stock_info(code, result):
    """
    处理股票信息，更新数据库。
    """
    try:
        exists = investment_recom_dao.exists(code)
        if exists:
            investment_recom_dao.update_frequency(code, result.get('当前价格'), result.get('TTM'))
        else:
            investment_recom_dao.save(code, result.get('股票名称'), result.get('当前价格'), result.get('TTM'))
    except IntegrityError as e:
        # 处理数据库完整性错误
        print(f"IntegrityError for code {code}: {e}")


if __name__ == '__main__':
    # 不要有中文符号
    directory = r'C:\Users\Administrator\Pictures\stockmarket\2025\tmp'
    process_jpg_files(directory)
